from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.models import db
from app.models.user import User
from sqlalchemy import text
from datetime import datetime

permissions_bp = Blueprint('permissions', __name__)

# 模块名称中文映射
MODULE_NAME_MAP = {
    'area': '区域管理',
    'user': '用户管理',
    'work_order': '工单管理',
    'material': '物料管理',
    'warehouse': '仓库管理',
    'system': '系统管理',
    'report': '报表管理',
    'permission': '权限管理',
    'role': '角色管理',
    'config': '配置管理',
    'group': '组织管理',
    'vehicle': '车辆管理'
}

def get_module_display_name(module):
    """获取模块的中文显示名称"""
    return MODULE_NAME_MAP.get(module, module)

@permissions_bp.route('', methods=['GET'])
@jwt_required()
def get_permissions():
    """获取权限列表"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'manager']:
            return jsonify({'error': '权限不足'}), 403
        
        module = request.args.get('module', '')
        search = request.args.get('search', '')
        
        # 构建查询条件
        conditions = []
        params = {}
        
        if module:
            conditions.append('module = :module')
            params['module'] = module
        
        if search:
            conditions.append('(name LIKE :search OR description LIKE :search)')
            params['search'] = f'%{search}%'
        
        where_clause = 'WHERE ' + ' AND '.join(conditions) if conditions else ''
        
        query = text(f"""
            SELECT id, name, code, module, description, is_active, created_at
            FROM permissions 
            {where_clause}
            ORDER BY module, name
        """)
        
        result = db.session.execute(query, params)
        permissions = []
        
        for row in result:
            permissions.append({
                'id': row.id,
                'name': row.name,
                'code': row.code,
                'module': row.module,
                'module_display': get_module_display_name(row.module),
                'description': row.description,
                'is_active': bool(row.is_active),
                'created_at': row.created_at.isoformat() if hasattr(row.created_at, 'isoformat') and row.created_at else str(row.created_at) if row.created_at else None
            })
        
        return jsonify({
            'permissions': permissions,
            'total': len(permissions)
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/modules', methods=['GET'])
@jwt_required()
def get_permission_modules():
    """获取权限模块列表"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'manager']:
            return jsonify({'error': '权限不足'}), 403
        
        query = text("""
            SELECT DISTINCT module, COUNT(*) as permission_count
            FROM permissions 
            WHERE is_active = 1
            GROUP BY module
            ORDER BY module
        """)
        
        result = db.session.execute(query)
        modules = []
        
        for row in result:
            modules.append({
                'module': row.module,
                'module_display': get_module_display_name(row.module),
                'permission_count': row.permission_count
            })
        
        return jsonify({'modules': modules}), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/roles/<role>/permissions', methods=['GET'])
@jwt_required()
def get_role_permissions(role):
    """获取角色权限"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'manager']:
            return jsonify({'error': '权限不足'}), 403
        
        query = text("""
            SELECT p.id, p.name, p.code, p.module, p.description, 
                   CASE WHEN rp.permission_id IS NOT NULL THEN 1 ELSE 0 END as has_permission
            FROM permissions p
            LEFT JOIN role_permissions rp ON p.id = rp.permission_id AND rp.role = :role
            WHERE p.is_active = 1
            ORDER BY p.module, p.name
        """)
        
        result = db.session.execute(query, {'role': role})
        permissions = []
        
        for row in result:
            permissions.append({
                'id': row.id,
                'name': row.name,
                'code': row.code,
                'module': row.module,
                'module_display': get_module_display_name(row.module),
                'description': row.description,
                'has_permission': bool(row.has_permission)
            })
        
        return jsonify({
            'role': role,
            'permissions': permissions,
            'total': len(permissions)
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/users/<int:user_id>/permissions', methods=['GET'])
@jwt_required()
def get_user_permissions(user_id):
    """获取用户权限（包括角色权限和特殊权限）"""
    try:
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        if not current_user or (current_user.role != 'admin' and int(current_user_id) != user_id):
            return jsonify({'error': '权限不足'}), 403
        
        target_user = User.query.get(user_id)
        if not target_user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 获取用户的所有权限（角色权限 + 特殊权限）
        query = text("""
            SELECT DISTINCT p.id, p.name, p.code, p.module, p.description,
                   CASE WHEN rp.permission_id IS NOT NULL THEN 'role' 
                        WHEN up.permission_id IS NOT NULL THEN 'user' 
                        ELSE NULL END as source
            FROM permissions p
            LEFT JOIN role_permissions rp ON p.id = rp.permission_id AND rp.role = :role
            LEFT JOIN user_permissions up ON p.id = up.permission_id AND up.user_id = :user_id
            WHERE p.is_active = 1 AND (rp.permission_id IS NOT NULL OR up.permission_id IS NOT NULL)
            ORDER BY p.module, p.name
        """)
        
        result = db.session.execute(query, {
            'role': target_user.role,
            'user_id': user_id
        })
        
        permissions = []
        for row in result:
            permissions.append({
                'id': row.id,
                'name': row.name,
                'code': row.code,
                'module': row.module,
                'module_display': get_module_display_name(row.module),
                'description': row.description,
                'source': row.source  # 'role' 或 'user'
            })
        
        return jsonify({
            'user_id': user_id,
            'username': target_user.username,
            'role': target_user.role,
            'permissions': permissions,
            'total': len(permissions)
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/users/<int:user_id>/check', methods=['POST'])
@jwt_required()
def check_user_permission(user_id):
    """检查用户是否有指定权限"""
    try:
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        if not current_user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 如果不是管理员且不是查询自己的权限，则拒绝
        if current_user.role != 'admin' and int(current_user_id) != user_id:
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        permission_codes = data.get('permission_codes', [])
        
        if not permission_codes:
            return jsonify({'error': '权限代码不能为空'}), 400
        
        target_user = User.query.get(user_id)
        if not target_user:
            return jsonify({'error': '目标用户不存在'}), 404
        
        # 检查权限
        results = {}
        for code in permission_codes:
            # 检查角色权限和用户特殊权限
            check_query = text("""
                SELECT COUNT(*) as count
                FROM permissions p
                LEFT JOIN role_permissions rp ON p.id = rp.permission_id AND rp.role = :role
                LEFT JOIN user_permissions up ON p.id = up.permission_id AND up.user_id = :user_id
                WHERE p.code = :code AND p.is_active = 1 
                  AND (rp.permission_id IS NOT NULL OR up.permission_id IS NOT NULL)
            """)
            
            result = db.session.execute(check_query, {
                'code': code,
                'role': target_user.role,
                'user_id': user_id
            })
            
            results[code] = result.scalar() > 0
        
        return jsonify({
            'user_id': user_id,
            'permissions': results
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/role-permissions', methods=['GET'])
@jwt_required()
def get_role_permissions_api():
    """获取角色权限 - 兼容前端API调用"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role not in ['admin', 'manager']:
            return jsonify({'error': '权限不足'}), 403
        
        role = request.args.get('role')
        if not role:
            return jsonify({'error': '角色参数不能为空'}), 400
        
        query = text("""
            SELECT p.id, p.name, p.code, p.module, p.description, 
                   CASE WHEN rp.permission_id IS NOT NULL THEN 1 ELSE 0 END as has_permission
            FROM permissions p
            LEFT JOIN role_permissions rp ON p.id = rp.permission_id AND rp.role = :role
            WHERE p.is_active = 1
            ORDER BY p.module, p.name
        """)
        
        result = db.session.execute(query, {'role': role})
        permissions = []
        
        for row in result:
            permissions.append({
                'id': row.id,
                'name': row.name,
                'code': row.code,
                'module': row.module,
                'module_display': get_module_display_name(row.module),
                'description': row.description,
                'has_permission': bool(row.has_permission)
            })
        
        return jsonify({
            'role': role,
            'permissions': permissions,
            'total': len(permissions)
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/role-permissions', methods=['POST'])
@jwt_required()
def set_role_permission_api():
    """设置角色权限 - 兼容前端API调用"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        role = data.get('role')
        permission_id = data.get('permission_id')
        is_granted = data.get('is_granted', True)
        
        if not role or not permission_id:
            return jsonify({'error': '角色和权限ID不能为空'}), 400
        
        # 验证角色
        valid_roles = ['admin', 'dispatcher', 'worker', 'warehouse_manager']
        if role not in valid_roles:
            return jsonify({'error': '无效的角色'}), 400
        
        if is_granted:
            # 添加权限
            insert_query = text("""
                INSERT OR IGNORE INTO role_permissions (role, permission_id, created_at)
                VALUES (:role, :permission_id, :created_at)
            """)
            db.session.execute(insert_query, {
                'role': role,
                'permission_id': permission_id,
                'created_at': datetime.now()
            })
        else:
            # 移除权限
            delete_query = text("""
                DELETE FROM role_permissions 
                WHERE role = :role AND permission_id = :permission_id
            """)
            db.session.execute(delete_query, {
                'role': role,
                'permission_id': permission_id
            })
        
        db.session.commit()
        
        return jsonify({'message': '角色权限设置成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/role-permissions/batch', methods=['POST'])
@jwt_required()
def batch_set_role_permissions_api():
    """批量设置角色权限 - 兼容前端API调用"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        role = data.get('role')
        permissions = data.get('permissions', [])
        
        if not role:
            return jsonify({'error': '角色不能为空'}), 400
        
        # 验证角色
        valid_roles = ['admin', 'dispatcher', 'worker', 'warehouse_manager']
        if role not in valid_roles:
            return jsonify({'error': '无效的角色'}), 400
        
        # 删除现有角色权限
        delete_query = text("""
            DELETE FROM role_permissions WHERE role = :role
        """)
        db.session.execute(delete_query, {'role': role})
        
        # 插入新的角色权限
        for perm in permissions:
            if perm.get('is_granted', False):
                insert_query = text("""
                    INSERT INTO role_permissions (role, permission_id, created_at)
                    VALUES (:role, :permission_id, :created_at)
                """)
                db.session.execute(insert_query, {
                    'role': role,
                    'permission_id': perm['permission_id'],
                    'created_at': datetime.now()
                })
        
        db.session.commit()
        
        return jsonify({'message': f'角色 {role} 权限批量设置成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/roles/<role>/permissions', methods=['POST'])
@jwt_required()
def assign_role_permissions(role):
    """分配角色权限"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        permission_ids = data.get('permission_ids', [])
        
        if not permission_ids:
            return jsonify({'error': '权限ID列表不能为空'}), 400
        
        # 验证角色
        valid_roles = ['admin', 'manager', 'user']
        if role not in valid_roles:
            return jsonify({'error': '无效的角色'}), 400
        
        # 删除现有角色权限
        delete_query = text("""
            DELETE FROM role_permissions WHERE role = :role
        """)
        db.session.execute(delete_query, {'role': role})
        
        # 插入新的角色权限
        for permission_id in permission_ids:
            insert_query = text("""
                INSERT INTO role_permissions (role, permission_id, created_at)
                VALUES (:role, :permission_id, :created_at)
            """)
            db.session.execute(insert_query, {
                'role': role,
                'permission_id': permission_id,
                'created_at': datetime.now()
            })
        
        db.session.commit()
        
        return jsonify({'message': f'角色 {role} 权限分配成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/users/<int:user_id>/permissions', methods=['POST'])
@jwt_required()
def assign_user_permissions(user_id):
    """分配用户特殊权限"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        permission_ids = data.get('permission_ids', [])
        
        # 验证目标用户
        target_user = User.query.get(user_id)
        if not target_user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 删除现有用户特殊权限
        delete_query = text("""
            DELETE FROM user_permissions WHERE user_id = :user_id
        """)
        db.session.execute(delete_query, {'user_id': user_id})
        
        # 插入新的用户特殊权限
        for permission_id in permission_ids:
            insert_query = text("""
                INSERT INTO user_permissions (user_id, permission_id, created_at)
                VALUES (:user_id, :permission_id, :created_at)
            """)
            db.session.execute(insert_query, {
                'user_id': user_id,
                'permission_id': permission_id,
                'created_at': datetime.now()
            })
        
        db.session.commit()
        
        return jsonify({'message': f'用户 {target_user.username} 特殊权限分配成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('', methods=['POST'])
@jwt_required()
def create_permission():
    """创建权限"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['name', 'code', 'module']
        for field in required_fields:
            if not data.get(field):
                return jsonify({'error': f'{field} 不能为空'}), 400
        
        # 检查权限代码是否已存在
        check_query = text("""
            SELECT COUNT(*) as count
            FROM permissions 
            WHERE code = :code
        """)
        
        result = db.session.execute(check_query, {'code': data['code']})
        if result.scalar() > 0:
            return jsonify({'error': '权限代码已存在'}), 400
        
        # 插入新权限
        insert_query = text("""
            INSERT INTO permissions (name, code, module, description, is_active, created_at)
            VALUES (:name, :code, :module, :description, :is_active, :created_at)
        """)
        
        db.session.execute(insert_query, {
            'name': data['name'],
            'code': data['code'],
            'module': data['module'],
            'description': data.get('description'),
            'is_active': data.get('is_active', True),
            'created_at': datetime.now()
        })
        
        db.session.commit()
        
        return jsonify({'message': '权限创建成功'}), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/<int:permission_id>', methods=['PUT'])
@jwt_required()
def update_permission(permission_id):
    """更新权限"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        data = request.get_json()
        
        # 检查权限是否存在
        check_query = text("""
            SELECT id FROM permissions WHERE id = :id
        """)
        
        result = db.session.execute(check_query, {'id': permission_id})
        if not result.fetchone():
            return jsonify({'error': '权限不存在'}), 404
        
        # 如果更新代码，检查是否重复
        if 'code' in data:
            code_check_query = text("""
                SELECT COUNT(*) as count
                FROM permissions 
                WHERE code = :code AND id != :id
            """)
            
            result = db.session.execute(code_check_query, {
                'code': data['code'],
                'id': permission_id
            })
            
            if result.scalar() > 0:
                return jsonify({'error': '权限代码已存在'}), 400
        
        # 构建更新字段
        update_fields = []
        params = {'id': permission_id}
        
        allowed_fields = ['name', 'code', 'module', 'description', 'is_active']
        for field in allowed_fields:
            if field in data:
                update_fields.append(f'{field} = :{field}')
                params[field] = data[field]
        
        if not update_fields:
            return jsonify({'error': '没有可更新的字段'}), 400
        
        # 执行更新
        update_query = text(f"""
            UPDATE permissions 
            SET {', '.join(update_fields)}
            WHERE id = :id
        """)
        
        db.session.execute(update_query, params)
        db.session.commit()
        
        return jsonify({'message': '权限更新成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/<int:permission_id>', methods=['DELETE'])
@jwt_required()
def delete_permission(permission_id):
    """删除权限"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        # 检查权限是否存在
        check_query = text("""
            SELECT id FROM permissions WHERE id = :id
        """)
        
        result = db.session.execute(check_query, {'id': permission_id})
        if not result.fetchone():
            return jsonify({'error': '权限不存在'}), 404
        
        # 删除相关的角色权限和用户权限
        delete_role_permissions = text("""
            DELETE FROM role_permissions WHERE permission_id = :permission_id
        """)
        db.session.execute(delete_role_permissions, {'permission_id': permission_id})
        
        delete_user_permissions = text("""
            DELETE FROM user_permissions WHERE permission_id = :permission_id
        """)
        db.session.execute(delete_user_permissions, {'permission_id': permission_id})
        
        # 删除权限
        delete_query = text("""
            DELETE FROM permissions WHERE id = :id
        """)
        db.session.execute(delete_query, {'id': permission_id})
        
        db.session.commit()
        
        return jsonify({'message': '权限删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@permissions_bp.route('/users/<int:user_id>/permissions/<int:permission_id>', methods=['DELETE'])
@jwt_required()
def remove_user_permission(user_id, permission_id):
    """删除用户特殊权限"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or user.role != 'admin':
            return jsonify({'error': '权限不足'}), 403
        
        # 验证目标用户
        target_user = User.query.get(user_id)
        if not target_user:
            return jsonify({'error': '用户不存在'}), 404
        
        # 检查权限是否存在
        permission_check = text("""
            SELECT id FROM permissions WHERE id = :permission_id
        """)
        result = db.session.execute(permission_check, {'permission_id': permission_id})
        if not result.fetchone():
            return jsonify({'error': '权限不存在'}), 404
        
        # 删除用户特殊权限
        delete_query = text("""
            DELETE FROM user_permissions 
            WHERE user_id = :user_id AND permission_id = :permission_id
        """)
        result = db.session.execute(delete_query, {
            'user_id': user_id,
            'permission_id': permission_id
        })
        
        if result.rowcount == 0:
            return jsonify({'error': '该用户没有此特殊权限'}), 404
        
        db.session.commit()
        
        return jsonify({'message': '用户特殊权限删除成功'}), 200
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500